package com.mjk.manager.centerconf.type;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.mjk.common.util.ReflectionUtils;
import com.mjk.manager.centerconf.dto.ConfDto;
import com.mjk.manager.centerconf.type.impl.*;
import lombok.Getter;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * 刷新内容
 * @author jafek
 *
 */
@Getter
public enum RefreshType {
	Default("", DefaultFiledRefreshImpl.class),
	TOMCAT("server.", TomcatRefreshImpl.class),
	RMQ("bee.rmq", RmqRefreshImpl.class),
	REDIS("bee.redis", RedisRefreshImpl.class),
	DB("sharding.jdbc", DBRefreshImpl.class)
	;
	private String key;
	private Class<?> type;
	RefreshType(String key,Class<?> type){
		this.key = key;
		this.type = type;
	}



	
	public static void doRefresh(AbstractApplicationContext context,Map<String,Object> refreshData,Map<String,Object> oldData){
		RefreshType[] ary = values();
        for (RefreshType refreshType : ary) {
            Object impl = context.getBean(refreshType.getType());
            ReflectionUtils.invoke(impl, "refresh", new Class[]{AbstractApplicationContext.class, Map.class, Map.class},
                    new Object[]{context, refreshData, oldData});
        }
	}
	/**
	 * 分类各个属性
     */
	public static Map<String,HashSet<ConfDto>> getConfTypeFields(List<ConfDto> lists){
		Map<String,HashSet <ConfDto>> map = new HashMap<>();
		RefreshType[] ary = values();
		HashSet <ConfDto> def = new HashSet<>(lists);
        for (RefreshType type : ary) {
            for (ConfDto dto : lists) {
                if (type != Default) {
                    if (dto.getName().startsWith(type.getKey()) && !ObjectUtils.isEmpty(type.getKey())) {
                        if (ObjectUtils.isEmpty(map.get(type.getKey()))) {
                            map.put(type.getKey(), new HashSet<>());
                        }
                        map.get(type.getKey()).add(dto);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(map.get(type.getKey())))
                def.removeAll(map.get(type.getKey()));
        }
		map.put(Default.getKey(), def);
		return map;
	}
}
